<template>
  <view class="container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-info">
        <image class="avatar" :src="userInfo.avatar" mode="aspectFill" @click="changeAvatar" />
        <view class="user-details">
          <view v-if="loggedIn" class="logged-in-info">
            <text class="nickname">{{ userInfo.nickname }}</text>
            <text class="username">{{ userInfo.username }}</text>
            <text class="user-type">{{ getUserTypeText(userInfo.userType) }}</text>
          </view>
          <view v-else class="not-logged-in-info">
            <text class="welcome-text">欢迎来到家电商城</text>
            <view class="login-links">
              <!-- <text @click="goToLogin">登录/注册 ></text> -->
              <text @click="goToLogin">登录 ></text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 佣金信息 - 仅销售人员显示 -->
    <view v-if="loggedIn && userInfo.userType === 'sales'" class="commission-card">
      <view class="commission-header">
        <text class="title">我的佣金</text>
        <text class="amount">¥{{ commissionInfo.total.toFixed(2) }}</text>
      </view>
      <!-- <view class="commission-stats">
        <view class="stat-item">
          <text class="stat-value">{{ commissionInfo.available }}</text>
          <text class="stat-label">可提现</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ commissionInfo.frozen }}</text>
          <text class="stat-label">冻结中</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ commissionInfo.totalWithdraw }}</text>
          <text class="stat-label">已提现</text>
        </view>
      </view> -->
      <!-- <view class="commission-actions">
        <button class="withdraw-btn" @click="goToWithdraw">立即提现</button>
        <button class="records-btn" @click="goToRecords">提现记录</button>
      </view> -->
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-title">我的服务</view>
      <view class="menu-grid">
        <view class="menu-item" @click="goToOrders">
          <view class="menu-icon order-icon">
            <uni-icons type="list" size="24" color="#fff"></uni-icons>
          </view>
          <text class="menu-text">意向订单</text>
        </view>

        <!-- <view class="menu-item" @click="goToFavorites">
          <view class="menu-icon favorite-icon">
            <uni-icons type="heart" size="24" color="#fff"></uni-icons>
          </view>
          <text class="menu-text">我的收藏</text>
        </view> -->

        <view class="menu-item" @click="goToPromotion" v-if="loggedIn && userInfo.userType === 'sales'">
          <view class="menu-icon promotion-icon">
            <image class="icon-image" src="/static/icons/promotion.svg" mode="aspectFit" />
          </view>
          <text class="menu-text">我的推广</text>
        </view>
      </view>
    </view>

    <!-- 其他功能 -->
    <view class="menu-section">
      <view class="menu-title">其他服务</view>
      <view class="menu-list">
        <view class="menu-list-item" @click="goToSettings">
          <view class="menu-list-icon">
            <uni-icons type="gear" size="20" color="#007AFF"></uni-icons>
          </view>
          <text class="menu-list-text">设置</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>

        <view class="menu-list-item" @click="generatePromotionCode" v-if="userInfo.userType === 'sales'">
          <view class="menu-list-icon">
            <uni-icons type="gift" size="20" color="#007AFF"></uni-icons>
          </view>
          <text class="menu-list-text">推广</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>

        <view class="menu-list-item" @click="goToAbout">
          <view class="menu-list-icon">
            <uni-icons type="info" size="20" color="#007AFF"></uni-icons>
          </view>
          <text class="menu-list-text">关于我们</text>
          <uni-icons type="right" size="16" color="#ccc"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 退出登录 -->
    <view v-if="loggedIn" class="logout-section">
      <button class="logout-btn" @click="logout">退出登录</button>
    </view>

    <!-- 二维码弹框 -->
    <uni-popup ref="qrPopup" type="center" @close="closeQrCode">
      <view class="qr-popup">
        <view class="qr-header">
          <text class="qr-title">我的推广码</text>
          <view class="qr-close" @click="closeQrCode">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="qr-content">
          <image v-if="qrCodeImage" class="qr-image" :src="qrCodeImage" mode="aspectFit" />
          <text class="qr-desc">扫描二维码，邀请好友注册</text>
          <text class="qr-tip">好友通过您的推广码注册，您将获得推广奖励</text>
        </view>
        <view class="qr-actions">
          <button class="qr-save-btn" @click="saveQrCode">保存到相册</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { onShow, onUnload } from '@dcloudio/uni-app';
import request from '@/utils/request';
import type { ImageResponse } from '@/utils/request';
import {
  isLoggedIn,
  getUserInfo,
  clearAuth,
  requireLogin,
  addAuthStateListener,
  removeAuthStateListener,
} from '@/utils/auth';
import type { UserInfo } from '@/utils/auth';

// 用户信息
const userInfo = ref<UserInfo>({
  id: 0,
  username: '',
  nickname: '',
  avatar: '/static/avatar.png',
  userType: 'normal',
  phone: '',
});

// 佣金信息
const commissionInfo = ref({
  total: 0.0,
  available: 0.0,
  frozen: 0.0,
  totalWithdraw: 0.0,
});

// 获取佣金数据
const getCommissionData = async () => {
  // 只有登录的销售人员才获取佣金数据
  if (!loggedIn.value || userInfo.value.userType !== 'sales') {
    return;
  }

  try {
    const response: any = await request({
      url: '/order/commission',
      method: 'GET',
    });

    console.log('佣金数据响应:', response);

    if (response.code === 200 && response.data !== null && response.data !== undefined) {
      // 将响应数据除以100并保留两位小数
      const commissionAmount = Number(response.data)  / 100;
      commissionInfo.value.total = Number(commissionAmount.toFixed(2));
    } else {
      // 失败时默认显示0
      commissionInfo.value.total = 0.0;
    }
  } catch (error) {
    console.error('获取佣金数据失败:', error);
    // 失败时默认显示0
    commissionInfo.value.total = 0.0;
  }
};

// 响应式的登录状态
const loggedIn = ref(false);

// 获取用户类型文本
const getUserTypeText = (userType: string) => {
  return userType === 'sales' ? '销售人员' : '普通用户';
};

// 检查登录状态
const checkLoginStatus = async () => {
  const isUserLoggedIn = isLoggedIn();
  const storedUserInfo = getUserInfo();

  // 更新登录状态
  loggedIn.value = isUserLoggedIn;

  if (storedUserInfo && isUserLoggedIn) {
    userInfo.value = {
      ...storedUserInfo,
      // userType: 'sales'
    };
  } else {
    // 未登录时重置用户信息
    userInfo.value = {
      id: 0,
      username: '',
      nickname: '',
      avatar: '/static/avatar.png',
      userType: 'normal',
      phone: '',
    };
  }

  console.log('登录状态检查:', {
    isLoggedIn: loggedIn.value,
    userType: userInfo.value.userType,
    userInfo: userInfo.value,
  });

  // 检查登录状态后，获取佣金数据
  await getCommissionData();
};

// 修改头像
const changeAvatar = () => {
  if (!requireLogin()) {
    return;
  }

  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      userInfo.value.avatar = tempFilePath;
      uni.showToast({
        title: '头像修改成功',
        icon: 'success',
      });
    },
  });
};

// 跳转到登录页面
const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/user/login',
  });
};

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/user/register',
  });
};


// 跳转到订单页面
const goToOrders = () => {
  if (!requireLogin()) {
    return;
  }
  uni.navigateTo({
    url: '/pages/user/orders',
  });
};

// 跳转到推广页面
const goToPromotion = () => {
  if (!requireLogin()) {
    return;
  }
  uni.navigateTo({
    url: '/pages/commission/promotion',
  });
};

// 设置
const goToSettings = () => {
  if (!requireLogin()) {
    return;
  }
  // 跳转到编辑基础信息页面
  uni.navigateTo({
    url: '/pages/user/edit-info',
  });
};

// 生成推广码
const generatePromotionCode = () => {
  if (!requireLogin()) {
    return;
  }
  generateQRCode();
};

// 二维码显示状态
const qrPopup = ref();
const qrCodeImage = ref('');

// 生成二维码
const generateQRCode = async () => {
  if (!requireLogin()) {
    return;
  }

  try {
    uni.showLoading({
      title: '生成中...',
    });

    const response = await request<ImageResponse>({
      url: '/qrcode',
      method: 'GET',
      header: {
        'Content-Type': 'image/png',
      },
    });

    console.log('二维码响应:', response);

    if (response.code === 200 && response.data.imageData) {
      // 设置二维码图片数据
      qrCodeImage.value = response.data.imageData;

      // 显示弹框
      qrPopup.value?.open();

      uni.showToast({
        title: '推广码生成成功',
        icon: 'success',
      });
    } else {
      uni.showToast({
        title: '生成推广码失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('生成二维码失败:', error);
    uni.showToast({
      title: '生成推广码失败',
      icon: 'none',
    });
  } finally {
    uni.hideLoading();
  }
};

// 关闭二维码弹框
const closeQrCode = () => {
  qrPopup.value?.close();
  qrCodeImage.value = '';
};

// 保存二维码到相册
const saveQrCode = async () => {
  if (!qrCodeImage.value) {
    uni.showToast({
      title: '二维码数据不存在',
      icon: 'none',
    });
    return;
  }

  try {
    // 显示加载提示
    uni.showLoading({
      title: '保存中...',
    });

    // 检查并请求相册权限
    const authResult = await checkAlbumAuth();
    if (!authResult) {
      uni.hideLoading();
      return;
    }

    // 处理base64数据
    let base64Data = qrCodeImage.value;
    if (base64Data.startsWith('data:image')) {
      base64Data = base64Data.replace(/^data:image\/\w+;base64,/, '');
    }

    // 获取临时文件路径
    const tempFilePath = `${wx.env.USER_DATA_PATH}/qrcode_${Date.now()}.png`;

    // 写入临时文件
    const fs = uni.getFileSystemManager();

    await new Promise((resolve, reject) => {
      fs.writeFile({
        filePath: tempFilePath,
        data: base64Data,
        encoding: 'base64',
        success: resolve,
        fail: reject,
      });
    });

    // 保存到相册
    await new Promise((resolve, reject) => {
      uni.saveImageToPhotosAlbum({
        filePath: tempFilePath,
        success: resolve,
        fail: reject,
      });
    });

    uni.hideLoading();
    uni.showToast({
      title: '保存成功',
      icon: 'success',
    });

    // 清理临时文件
    setTimeout(() => {
      fs.unlink({
        filePath: tempFilePath,
        success: () => console.log('临时文件已清理'),
        fail: (err) => console.warn('清理临时文件失败:', err),
      });
    }, 1000);
  } catch (error) {
    uni.hideLoading();
    console.error('保存二维码失败:', error);

    let errorMessage = '保存失败';
    if (error && typeof error === 'object') {
      const err = error as any;
      if (err.errMsg) {
        if (err.errMsg.includes('auth')) {
          errorMessage = '请授权访问相册';
        } else if (err.errMsg.includes('system')) {
          errorMessage = '系统错误，请重试';
        } else {
          errorMessage = '保存失败，请重试';
        }
      }
    }

    uni.showToast({
      title: errorMessage,
      icon: 'none',
      duration: 2000,
    });
  }
};

// 检查相册权限
const checkAlbumAuth = async (): Promise<boolean> => {
  return new Promise((resolve) => {
    uni.getSetting({
      success: (res) => {
        if (res.authSetting['scope.writePhotosAlbum'] === false) {
          // 用户之前拒绝了权限，引导用户手动开启
          uni.showModal({
            title: '需要相册权限',
            content: '保存二维码需要访问您的相册，请在设置中开启权限',
            confirmText: '去设置',
            success: (modalRes) => {
              if (modalRes.confirm) {
                uni.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.writePhotosAlbum']) {
                      resolve(true);
                    } else {
                      resolve(false);
                    }
                  },
                  fail: () => resolve(false),
                });
              } else {
                resolve(false);
              }
            },
          });
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          // 首次请求权限
          uni.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => resolve(true),
            fail: () => {
              uni.showModal({
                title: '需要相册权限',
                content: '保存二维码需要访问您的相册',
                success: (modalRes) => {
                  resolve(modalRes.confirm);
                },
              });
            },
          });
        } else {
          // 已经有权限
          resolve(true);
        }
      },
      fail: () => resolve(false),
    });
  });
};

// 关于我们
const goToAbout = () => {
  if (!requireLogin()) {
    return;
  }
  uni.showModal({
    title: '关于我们',
    content: '家电商城 v1.0.0\n\n为您提供优质的家电产品和服务',
    showCancel: false,
    confirmText: '确定',
  });
};

// 退出登录
const logout = () => {
  uni.showModal({
    title: '退出登录',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 使用新的清除登录信息方法
        clearAuth();

        // 更新响应式状态
        loggedIn.value = false;
        userInfo.value = {
          id: 0,
          username: '',
          nickname: '',
          avatar: '/static/avatar.png',
          userType: 'normal',
          phone: '',
        };

        uni.showToast({
          title: '已退出登录',
          icon: 'success',
        });
      }
    },
  });
};

// 认证状态监听器
const authStateListener = async () => {
  await checkLoginStatus();
};

onMounted(async () => {
  await checkLoginStatus();
  // 添加认证状态监听器
  addAuthStateListener(authStateListener);
});

onShow(async () => {
  await checkLoginStatus();
});

onUnmounted(() => {
  // 移除认证状态监听器
  removeAuthStateListener(authStateListener);
});

onUnload(() => {
  // 离开页面时清空推广码相关数据
  qrPopup.value?.close();
  qrCodeImage.value = '';
  console.log('离开profile页面，推广码数据已清空');
});
</script>

<style scoped>
.container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

.user-card {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  padding: 40rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
  border-top: 1rpx solid #fff;
}

.user-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 30rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-details {
  flex: 1;
}

.logged-in-info {
  display: flex;
  flex-direction: column;
}

.nickname {
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.username {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 5rpx;
}

.user-type {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.7);
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4rpx 12rpx;
  border-radius: 10rpx;
  align-self: flex-start;
  width: fit-content;
}

.not-logged-in-info {
  display: flex;
  flex-direction: column;
}

.welcome-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.login-links {
  display: flex;
  align-items: center;
}

.login-links text {
  font-size: 28rpx;
  color: #fff;
  /* text-decoration: underline; */
}

.commission-card {
  background-color: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.commission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* margin-bottom: 30rpx; */
}

.commission-header .title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.commission-header .amount {
  font-size: 48rpx;
  font-weight: bold;
  color: #ff6b35;
}

.commission-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.commission-actions {
  display: flex;
  gap: 20rpx;
}

.withdraw-btn,
.records-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.withdraw-btn {
  background-color: #ff6b35;
  color: #fff;
}

.records-btn {
  background-color: #f0f0f0;
  color: #333;
}

.menu-section {
  background-color: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.menu-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30rpx;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15rpx;
}

.menu-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.order-icon {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
}

.favorite-icon {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
}

.address-icon {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
}

.commission-icon {
  background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
}

.promotion-icon {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
}

.icon-image {
  width: 40rpx;
  height: 40rpx;
}

.menu-text {
  font-size: 24rpx;
  color: #333;
}

.menu-list {
  display: flex;
  flex-direction: column;
}

.menu-list-item {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.menu-list-item:last-child {
  border-bottom: none;
}

.menu-list-icon {
  margin-right: 20rpx;
}

.menu-list-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.logout-section {
  padding: 40rpx 20rpx;
}

.logout-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #fff;
  color: #ff4757;
  font-size: 32rpx;
  border: 1rpx solid #ff4757;
  border-radius: 44rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

/* 二维码弹框样式 */
.qr-popup {
  width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.qr-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.qr-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.qr-close {
  padding: 10rpx;
}

.qr-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 30rpx;
}

.qr-image {
  width: 400rpx;
  height: 400rpx;
  margin-bottom: 30rpx;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.qr-desc {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  text-align: center;
}

.qr-tip {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  line-height: 1.5;
}

.qr-actions {
  padding: 0 30rpx 30rpx;
}

.qr-save-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #ff6b35;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  border: none;
}
</style>
